#include "speech.h"
#include "mainwindow.h"
Speech::Speech(MainWindow *parent) : QObject(parent),m_parent(parent)
{

}
int Speech::detectKey()
{
    /**判断是否填充过秘钥**/
    QFile client_idFile("/root/client_id.txt");
    if(client_idFile.exists()){
        client_idFile.open(QIODevice::ReadWrite);
        QByteArray cli_id = client_idFile.readAll();
        if (!cli_id.isEmpty() && cli_id.endsWith('\n')) {
            cli_id.chop(1); // 删除末尾的换行符
        }
        client_id = cli_id;
        client_idFile.close();
    }else{
        QMessageBox::warning(m_parent, "警告", "没有找到client_id.txt，请关闭程序在root目录下创建");
        return -1;
    }

    QFile secret_idFile("/root/secret_id.txt");
    if(secret_idFile.exists()){
        secret_idFile.open(QIODevice::ReadWrite);
        QByteArray sec_id = secret_idFile.readAll();
        if (!sec_id.isEmpty() && sec_id.endsWith('\n')) {
            sec_id.chop(1); // 删除末尾的换行符
        }
        client_secret = sec_id;
        secret_idFile.close();
    }else{
        QMessageBox::warning(m_parent, "警告", "没有找到secret_id.txt，请关闭程序在root目录下创建");
        return -1;
    }
    return 0;
}
QString Speech::speechIdentify(QString fileName)
{
    int i;
    i = detectKey();
    if(i){
        return "填充密钥错误";
    }
//    获取Access Token
    QString tokenUrl =QString(baiduTokenUrl).arg(client_id).arg(client_secret);
    Http my_http;
    QMap<QString,QString>header;
    header.insert(QString("Content-Type"),QString("audio/pcm;rate=16000"));
    QByteArray requestData;//请求内容
    QByteArray replyData;//url返回内容

   qDebug()<<tokenUrl;
    bool result = my_http.post_sync(tokenUrl,header,requestData,replyData);
    if(result) {
        QString key = "access_token";
        QString accessToken =getJsonValue(replyData,key);
        qDebug()<<accessToken;
        //    语音识别
        QString speechUrl = QString(baiduSpeechUrl).arg(QHostInfo::localHostName()).arg(accessToken);
        QFile file;
        file.setFileName(fileName);
        file.open(QIODevice::ReadOnly);
        requestData = file.readAll();
        file.close();


        replyData.clear();
//        再次发起请求
        result = my_http.post_sync(speechUrl,header,requestData,replyData);
         if(result) {
             QString key = "result";
             QString retText =getJsonValue(replyData,key);
             qDebug()<<retText;
             return retText;
         }
         else{
             return nullptr;
         }
    }
    else {
        return  "error";
    }
}
QString Speech::getJsonValue(QByteArray ba,QString key)
{
    QJsonParseError parseError;
    QJsonDocument jsondocument = QJsonDocument::fromJson(ba,&parseError);
    if(parseError.error ==QJsonParseError::NoError)
    {
        if(jsondocument.isObject())
        {
            QJsonObject jsonObject = jsondocument.object();
            if(jsonObject.contains(key)){
                QJsonValue jsonvalue = jsonObject.value(key);
                if(jsonvalue.isString())
                    return jsonvalue.toString();
                else if(jsonvalue.isArray()){
                    QJsonArray arr = jsonvalue.toArray();
                    QJsonValue val =arr.at(0);
                    return val.toString();
                }

            }

        }
    }
    return NULL;

}
